package com.xky.example_student.controller;

import com.xky.example_student.entity.Result;
import com.xky.example_student.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/admin/permissions")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @GetMapping("")
    public Result<Map<String, Boolean>> getPermissions() {
        try {
            Map<String, Boolean> permissions = permissionService.getAllPermissions();
            return Result.success(permissions);
        } catch (Exception e) {
            return Result.error("获取权限设置失败");
        }
    }

    @PostMapping("/update")
    public Result<String> updatePermission(@RequestBody Map<String, Object> params) {
        try {
            String role = (String) params.get("role");
            String type = (String) params.get("type");
            Boolean value = (Boolean) params.get("value");

            // 构建权限key
            String permissionKey = role + type.substring(0, 1).toUpperCase() + type.substring(1);
            
            boolean success = permissionService.updatePermission(permissionKey, value);
            if (success) {
                return Result.success("权限更新成功");
            } else {
                return Result.error("权限更新失败");
            }
        } catch (Exception e) {
            return Result.error("权限更新失败：" + e.getMessage());
        }
    }

    @PostMapping("/initialize")
    public Result<String> initializePermissions() {
        try {
            permissionService.initializeDefaultPermissions();
            return Result.success("权限初始化成功");
        } catch (Exception e) {
            return Result.error("权限初始化失败：" + e.getMessage());
        }
    }
}
